<template>
 <div class="dept_manage">
    <!--配置prop：api方法能用,比如重置，校验-->
    <div class="query-form">
      <el-form :inline="true" ref="refQueryForm" :model="queryForm">
        <el-form-item prop="deptName" label="部门名称">
          <el-input
            v-model.trim="queryForm.deptName"
            placeholder="请输入部门名称"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getDeptList">查询</el-button>
          <el-button @click="handleReset('refQueryForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="action">
        <el-button  type="primary" @click="handleAdd"
          >创建</el-button
        >
      </div>
      <el-table
        :data="deptList"
        row-key="_id"
        :tree-props="{ children: 'children' }"
        stripe
        default-expand-all
        :expand-row-keys="[]"
      >
        <el-table-column v-for="item in columns" :key="item.prop" v-bind="item">
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button
              @click="handleEdit(scope.row)"
              size="mini"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      :title="action === 'add' ? '创建部门' : '部门编辑'"
      v-model="showModel"
    >
      <el-form
        ref="refdeptForm"
        :model="deptForm"
        :rules="deptRules"
        label-width="100px"
      >
        <el-form-item label="上级部门" prop="parentId">
          <el-cascader
            v-model="deptForm.parentId"
            placeholder="请选择部门"
            :options="deptList"
            :props="{
              value: '_id',
              label: 'deptName',
              checkStrictly: true,
            }"
            clearable
            style="margin-right: 10px; width: 320px"
          />
          <span>不选，则直接创建一级部门</span>
        </el-form-item>
        <el-form-item label="部门名称" prop="deptName">
          <el-input
            v-model.trim="deptForm.deptName"
            placeholder="请输入部门名称"
          />
        </el-form-item>
        <el-form-item label="负责人" prop="userName">
          <el-select
            v-model="deptForm.userName"
            filterable
            remote
            reserve-keyword
            placeholder="请输入用户名"
            :remote-method="remoteMethod"
            :loading="loading"
            style="width: 320px"
            @change="checkedCurUser"
          >
            <el-option
              v-for="item in allUserList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人邮箱" prop="userEmail">
          <el-input
            v-model="deptForm.userEmail"
            placeholder="请选择负责人"
            disabled
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="handleConfirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { toRaw } from "vue";
import utils from "../utils/utils";
export default {
  name: "Dept",
  data() {
    return {
      queryForm: {
        deptName: "",
      },
      deptList: [],
      deptForm: {
        parentId: [null],
        deptName: "",
        userId: "",
        userName: "",
        userEmail: "",
      },
      deptRules: {
        parentId: [
          { required: true, message: "请选择上级部门", trigger: "blur" },
        ],
        deptName: [
          { required: true, message: "请输入部门名称", trigger: "blur" },
        ],
        userName: [
          { required: true, message: "请选择负责人", trigger: "blur" },
        ],
      },
      showModel: false,
      action: "",
      allUserList: [],
      checkUserList: [],
      loading: false,
      columns: [
        {
          label: "部门名称",
          prop: "deptName",
        },
        {
          label: "负责人",
          prop: "userName",
        },
        {
          label: "创建时间",
          prop: "createTime",
          formatter(row, column, value) {
            //规范化时间格式
            // return utils.formateDate(value);
          },
        },
        {
          label: "更新时间",
          prop: "updateTime",
          formatter(row, column, value) {
            //规范化时间格式
            // return utils.formateDate(value);
          },
        },
      ],
    };
  },
  mounted() {
    this.getDeptList(); //获取部门列表
    this.getAllUserList(); //获取所有用户
    /*     this.menuList = this.$store.state.menuList; //获取菜单列表 */
  },
  methods: {
    async getAllUserList() {
      //获取所有用户列表
      const res = await this.$api.getUserAllList();
      this.allUserList = res;
    },
    async getDeptList() {
      //获取部门列表
      try {
        const params = { ...this.queryForm };
        const res = await this.$api.getDeptList(params);

        this.$store.commit("changeDeptList", res.data); //派发commit修改store数据

        this.deptList = res;
        console.log(this.deptList);
      } catch (error) {
        throw new Error(error);
      }
    },
    //重置
    handleReset(from) {
      this.$refs[from].resetFields();
      this.getDeptList(); //更新部门
    },
    handleAdd() {
      this.showModel = true;
      this.action = "add";
    },
    handleEdit(row) {
      //编辑
      this.action = "edit";
      this.showModel = true;
      console.log(row);
      this.$nextTick(() => {
        //将回调延迟到下次 DOM 更新循环之后执行,有“延迟”的意思
        Object.assign(this.deptForm, row);
      });
    },
    async handleDelete(row) {
      //删除
      const params = { ...row };
      params.action = "delete";
      const res = await this.$api.deptSubmit(params); //删除
      this.$msg.success({
        //提示
        message: res.msg || `删除成功`,
        duration: 1000,
      });
      this.getDeptList(); //更新部门
    },
    handleCancel() {
      this.showModel = false;
      this.handleReset("refdeptForm"); //重置表单
    },
    handleConfirm() {
      //新建、编辑部门
      this.$refs.refdeptForm.validate(async (valid) => {
        if (valid) {
          const body = this.deptForm; //携带数据
          body.action = this.action;
          //发送请求
          const res = await this.$api.deptSubmit(body);
          this.showModel = false; //关闭弹窗
          this.$msg.success(res.msg || "部门创建成功");
          this.handleReset("refdeptForm"); //重置表单
        } else {
          return false;
        }
      });
    },
    remoteMethod(query) {
      //输入框变化检索所有用户表
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.checkUserList = this.allUserList.filter((item) => {
            return (
              item.userName.toLowerCase().indexOf(query.toLowerCase()) > -1
            );
          });
        }, 200);
      } else {
        this.checkUserList = [];
      }
    },
    //选中的部门负责人
    checkedCurUser() {
      //按条件过滤数组，返回符合条件的新数组
      const curUser = this.allUserList.filter((item) => {
        return item.userName === this.deptForm.userName;
      });
      this.deptForm.userId = curUser[0].userId;
      this.deptForm.userEmail = curUser[0].userEmail;
    },
  },
};
</script>
<style lang="scss" scoped></style>